//
//  MessageSessionDao.m
//  SouthChina
//
//  Created by creator_lq on 14/12/4.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "MessageSessionDao.h"
#import "ContactDao.h"
#import "Class+Plugins.h"
#import "PublicAccount.h"
#import "PublicAccountDao.h"
#import "Contact.h"

@implementation MessageSessionDao

+(Message*)updataDBwithSQLiteStatement:(NSDictionary*)msgAllInfoMap{
    
    NSDictionary * msgContentTemp = [msgAllInfoMap objectForKey:@"content"];
    
    NSMutableDictionary *msgContent = [[NSMutableDictionary alloc] initWithDictionary:msgContentTemp];
    // 第一步：获取sessionid
    NSString *sessionId = [self generatSessionId:msgContent];
    
    // 第二步：创建或者更新seesion
    MessageSession * mesSession = [self queryForId:sessionId];
    if(mesSession==nil){
        mesSession = [self createSessionFromMessage:msgContent];
    }else {
        [self updateMessageSession:msgContent session:mesSession];
    }
    
    //20150818 陌生群暂时屏蔽掉，不入库
    if(mesSession == nil)
    {
        return  nil;
    }
    // 修改群组sesion的参会人员
    [self addGrupContact:mesSession messageMap:msgContent];
    [self updateMessageSession:mesSession];
    
    // 第三步:消息入库
    [msgContent setObject:mesSession.isremind forKey:@"isremind"];
    NSDate *updateTime = [[msgAllInfoMap objectForKey:@"update_time"]dateFromString];
    Message *msage = [[Message alloc] initWithData:msgContent msgId:[msgAllInfoMap objectForKey:@"id"] updateTime:updateTime seesionID:mesSession.sess_id];
    [MessageDao insertMessage2DB:msage];
    
    //签收到消息后，广播消息
    [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
    return msage;
    
    
}

+(NSString*)generatSessionId:(NSDictionary*)msgMap{
    // p2p,p2g消息(非系统消息)
    if ([MESSAGE_TYPE_P2P isEqualToString:[msgMap objectForKey:@"messageType"]]||[MESSAGE_TYPE_P2G isEqualToString:[msgMap objectForKey:@"messageType"]]) {
        return [NSString stringWithFormat:@"%@_%@",[msgMap objectForKey:@"messageType"],[self getOppositeId:msgMap]];
    }
    //系统消息
    else{
        // 如果是好友验证消息\邀请入群消息\批准申请入群消息(需要操作，所以分开处理)
        if([MESSAGE_TYPE_FRIEND isEqualToString:[msgMap objectForKey:@"businessId"]]||
           [SEND_JOIN_GRP_REQUEST isEqualToString:[msgMap objectForKey:@"businessId"]] ||
           [APPLY_TO_JOIN_GROUP isEqualToString:[msgMap objectForKey:@"businessId"]])
        {
            return [NSString stringWithFormat:@"%@_%@",[msgMap objectForKey:@"messageType"],[msgMap objectForKey:@"businessId"]];
        }
        //否则，无需操作，只需要展示
        else{
            
            return [NSString stringWithFormat:@"%@_%@",[msgMap objectForKey:@"messageType"],@"system"];

        }
    }
}

+(NSString *)getOppositeId:(NSDictionary*) msgMap{
    
    NSString *oppositeId = @"0";
    // 如果是群发消息，则对方id为群组id
    if([MESSAGE_TYPE_P2G isEqualToString:[msgMap objectForKey:@"messageType"]]){
        if([DE.userId isEqualToString:[msgMap objectForKey:@"senderId"]]){
            oppositeId = [msgMap objectForKey:@"groupId"];
        }else{
            oppositeId = [msgMap objectForKey:@"groupId"];
            /*NSArray *array = [oppositeId componentsSeparatedByString:@"_"];
            NSString *lastOne= [array objectAtIndex:[array count]-1];
            oppositeId = [oppositeId stringByReplacingOccurrencesOfString:lastOne withString:DE.userId];*/
        }
        return  oppositeId;
    }
    // 如果是点对点消息，则...
    else if ([MESSAGE_TYPE_P2P isEqualToString:[msgMap objectForKey:@"messageType"]]) {
        // 如果发送放是自己，那么对方就是接收的ID
        if ([DE.userId isEqualToString:[msgMap objectForKey:@"senderId"]]) {
            oppositeId = [msgMap objectForKey:@"receiverId"];
        }
        // 如果发送费是别人
        else{
            // 如果自己就是接收方，那么对方就是发送者
            if ([DE.userId isEqualToString:[msgMap objectForKey:@"receiverId"]]) {
                oppositeId = [msgMap objectForKey:@"senderId"];
                
            }else{
                oppositeId = [msgMap objectForKey:@"receiverId"];
                
            }
        }
        return oppositeId;

    }
    return [msgMap objectForKey:@"messageType"];
}

+(MessageSession*)queryForId:(NSString *)sessionId{
    
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    
    [self checkTableCreatedInDb:_dataBase];
    
    NSString *sesionSql  =@"SELECT * from messagesession where sess_id=?";

    FMResultSet *rs=[_dataBase executeQuery:sesionSql,sessionId];
    MessageSession *session = nil;
    
    while ([rs next]) {
        session = [[MessageSession alloc] init];
        session.sess_id = [rs stringForColumn:SESS_ID];
        session.sessionPic = [rs stringForColumn:SESSPICTURE];
        session.text = [rs stringForColumn:TEXT];
        session.title = [rs stringForColumn:TITLE];
        session.badgeNumber = [rs intForColumn:BADGENUMBER];
        session.sessionType = [rs stringForColumn:SESSIONTYPE];
        session.oppositeId = [rs stringForColumn:OPPOSITEID];
        session.isremind = [rs stringForColumn:ISREMIND];
        session.upate_time=[rs dateForColumn:UPDATE_TIME];
        session.otherInfo =[rs stringForColumn:OTHER_INFO];
    };
    [rs close];
    [_dataBase close];
    return session;

}

+(MessageSession*)createSessionFromMessage:(NSDictionary*)msgMap{
    
    NSString* session_id = [self generatSessionId:msgMap];
    
    NSDictionary *otherInfo = nil;
    NSString* messageType = [msgMap objectForKey:@"messageType"];
    NSString* sessionType = messageType;
    NSString* receiverId =  [msgMap objectForKey:@"receiverId"];
    NSString* text = @"";
    NSString* oppositeId = [self getOppositeId:msgMap];
    NSLog(@"XXXXXXXXXXXXXXX %@",oppositeId);
    NSString* isremind = @"1";
    NSString* sessionPic = @"";
    NSString* title = @"";
    
    NSString* senderId = [msgMap objectForKey:@"senderId"];
    NSString* groupId = [msgMap objectForKey:@"groupId"];
    
    NSLog(@"消息类型：%@  businessID:%@",sessionType,[msgMap objectForKey:@"businessId"]);


    if ([MESSAGE_TYPE_P2P isEqualToString: messageType]) {
        // 公众号的头像
        if ([senderId hasPrefix:@"PUB"]) {
            NSLog(@"公众号消息");
            PublicAccount *publicAccount = [PublicAccountDao queryForId:senderId];
            if (publicAccount) {
                sessionPic = publicAccount.headImg;
                title = publicAccount.appName;
            } else {
                sessionPic = @"";
                title = @"陌生公众号消息";
                otherInfo =  @{@"stranger":@"1"};
            }
        }
        // 联系人的头像
        else{
            
            Contact *contact = [ContactDao getContactById:senderId];
            if(contact){
                sessionPic = contact.mHEAD_IMG;
                title = contact.mNAME;
            }
            else {
                sessionPic = @"";
                title = @"陌生人消息";
                otherInfo = @{@"stranger":@"1"};
             }
        }
    }
    else if([MESSAGE_TYPE_P2G isEqualToString: messageType]){
        // 根据群组ID查找，群组在数据库中只有一个,如果群消息是自己发送的，那么groupID就是消息的接收者，如果不是自己发送的，就是消息的groupId
        NSString *myGroupID = @"";
        if ([DE.userId isEqualToString:senderId]) {
            myGroupID = receiverId;
        }
        else {
            /*NSArray *array = [groupId componentsSeparatedByString:@"_"];
            NSString *lastOne= [array objectAtIndex:[array count]-1];
            myGroupID = [groupId stringByReplacingOccurrencesOfString:lastOne withString:DE.userId];*/
            //20150815暂时这样改着
            myGroupID = groupId;
        }
        // 查找出消息发送的群组在我的通讯录中的信息
        Contact *contact = [ContactDao getContactById:myGroupID];
        if (contact) {
            sessionPic = contact.mHEAD_IMG;
            title = contact.mNAME;
        } else {
            title = @"陌生群组";
            otherInfo = @{@"stranger":@"1"};
        }
        // 设置该session的消息是否需要提示:是用户群组而且是设置不提示消息的
        if (contact != nil && [myGroupID containsString:@"usergrp"] && [@"0" isEqualToString:contact.mIS_ACTIVATED]) {
            NSLog(@"设置了消息免打扰");
            isremind = @"0";
        }
        oppositeId = myGroupID;
    }
    
    
    else if ([MESSAGE_TYPE_CMD isEqualToString: messageType]) {
        
         NSDictionary * contentMap = [[msgMap objectForKey:@"detail"] objectFromJSONString];
        if ([@"friendValidate" isEqualToString: [msgMap objectForKey:@"businessId"]]) {
            sessionPic = [contentMap objectForKey:@"headImg"];
            title =[NSString stringWithFormat:@"好友验证：%@",[contentMap objectForKey:@"userName"]];
            sessionType = MESSAGE_TYPE_FRIEND;
        }else if([@"sendJoinGrpRequest" isEqualToString: [msgMap objectForKey:@"businessId"]])//邀请入群系统消息
        {
            sessionPic = [contentMap objectForKey:@"headImg"];
            title =@"入群邀请";
            sessionType = SEND_JOIN_GRP_REQUEST;
                                        
            
        }else if([@"applyToJoinGrp" isEqualToString: [msgMap objectForKey:@"businessId"]]) //申请入群消息
        {
           
            title =[NSString stringWithFormat:@"入群申请：%@",[contentMap objectForKey:@"userName"]];
            sessionPic = [contentMap objectForKey:@"headImg"];
            sessionType = APPLY_TO_JOIN_GROUP;
        }
        else {
            sessionPic = [contentMap objectForKey:@"headImg"];
            title = @"系统消息";
        }
        
    }
    
    if (![MEDIATYPE_TEXT isEqualToString:[msgMap objectForKey:@"mediaType"]]) {
        text = @"{多媒体消息}";
    } else {
        text = [msgMap objectForKey:@"text"];
    }

    NSDate *updateTime = [[NSString stringWithFormat:@"%@",[msgMap objectForKey:@"sendTime"]] dateFromString];
    
    //20150818暂时屏蔽掉陌生群消息
    if([title isEqualToString:@"陌生群组"])
    {
        return nil;
    }
    MessageSession *session = [[MessageSession alloc] initWithData:session_id sesType:sessionType oppositeId:oppositeId title:title text:text sessionPic:sessionPic isremind:isremind updatime:updateTime otherInfo:otherInfo];
    
    return session;
}

+(void)updateMessageSession:(NSDictionary *)msgMap session:(MessageSession *)session{
    
    // 自己发送的消息就不用加1
    if (![DE.userId isEqualToString:[msgMap objectForKey:@"senderId"]]) {
        ++session.badgeNumber;
//        NSLog(@"badgeNumber==========%d",session.badgeNumber);
    }
    
    // 如果是系统消息
    if([MESSAGE_TYPE_CMD isEqualToString:[msgMap objectForKey:@"messageType"]]){
         NSDictionary * contentMap = [[msgMap objectForKey:@"detail"] objectFromJSONString];
        // 是好友验证消息
        if([@"friendValidate" isEqualToString:[msgMap objectForKey:@"businessId"]]){
            session.text =[msgMap objectForKey:@"text"];
            session.sessionPic =[contentMap objectForKey:@"headImg"];
            session.title = [NSString stringWithFormat:@"好友验证:%@",[contentMap objectForKey:@"userName"]];
        }
        else if([@"sendJoinGrpRequest" isEqualToString: [msgMap objectForKey:@"businessId"]])//邀请入群系统消息
        {
            session.sessionPic =[contentMap objectForKey:@"headImg"];
            session.text =[msgMap objectForKey:@"text"];
        }else if([@"applyToJoinGrp" isEqualToString: [msgMap objectForKey:@"businessId"]]) //申请入群消息
        {
            session.text =[msgMap objectForKey:@"text"];
            session.sessionPic =[contentMap objectForKey:@"headImg"];
            session.title = [NSString stringWithFormat:@"入群申请：%@",[contentMap objectForKey:@"userName"]];
        }
        else {
            session.sessionPic =[contentMap objectForKey:@"headImg"];
            session.text = [msgMap objectForKey:@"text"];
        }
    }
    
    // 如果非文字消息
    else {
        if (![MEDIATYPE_TEXT isEqualToString:[msgMap objectForKey:@"mediaType"]]) {
            session.text = @"{多媒体消息}";
        } else {
            session.text = [msgMap objectForKey:@"text"];
            NSString* senderId = [msgMap objectForKey:@"senderId"];
            //如果是p2p消息，需要从本地重新更新下用户头像
            if([MESSAGE_TYPE_P2P isEqualToString:[msgMap objectForKey:@"messageType"]])
            {
                NSLog(@"*********p2p更新文字信息等*********");
                Contact *contact = [ContactDao getContactById:senderId];
                if(contact)
                    session.sessionPic = contact.mHEAD_IMG;
            }
            else if([MESSAGE_TYPE_P2G isEqualToString:[msgMap objectForKey:@"messageType"]])
            {
               NSLog(@"*********p2g更新文字信息等*********");
               NSString* groupId = [msgMap objectForKey:@"groupId"];
               NSString* receiverId =  [msgMap objectForKey:@"receiverId"];
               NSString *myGroupID = @"";
                if ([DE.userId isEqualToString:senderId]) {
                    myGroupID = receiverId;
                }
                else {
                   myGroupID = groupId;
                }
                // 查找出消息发送的群组在我的通讯录中的信息
                Contact *contact = [ContactDao getContactById:myGroupID];
                if (contact) {
                    session.sessionPic = contact.mHEAD_IMG;
                    session.title = contact.mNAME;
                    if ([@"0" isEqualToString:contact.mIS_ACTIVATED]) {
                        NSLog(@"设置了session.isremind消息免打扰");
                        session.isremind = @"0";
                    }
                }
            }
            
        }
    }
    
    NSString *time = [msgMap objectForKey:@"sendTime"] == nil ? [msgMap objectForKey:@"update_time"]: [msgMap objectForKey:@"sendTime"];
    session.upate_time = [time dateFromString];
 }

+(void)addGrupContact:(MessageSession*)msgSesion messageMap:(NSDictionary*) msgMap{
    
    if ([MESSAGE_TYPE_P2G isEqualToString:msgSesion.sessionType]) {
        NSDictionary* grupContacts = nil;
        if (![msgSesion getValue:@"grupContacts"]) {
            grupContacts = [[NSMutableDictionary alloc] initWithCapacity:10];
            [msgSesion putValue:grupContacts key:@"grupContacts"];
        }else {
            grupContacts = [[NSMutableDictionary alloc] initWithDictionary:[msgSesion getValue:@"grupContacts"]];
        }
        
   
        // 没有添加发送者信息，不是自己发送的，群组的id不为空
        if (![DE.userId isEqualToString:[msgMap objectForKey:@"senderId"]]
            && [msgMap objectForKey:@"groupId"] &&![grupContacts objectForKey:[msgMap objectForKey:@"senderId"]] ){
            
             // 消息中自带了发送者想信息
            if(!strIsEmpty([msgMap objectForKey:@"senderName"])&&!strIsEmpty([msgMap objectForKey:@"senderHeadImg"])){
                NSDictionary *contacInfo = @{@"senderName":[msgMap objectForKey:@"senderName"],@"senderHeadImg":[msgMap objectForKey:@"senderHeadImg"]};
                [grupContacts setValue:contacInfo forKey:@"senderId"];
            }
            
            // 从本地库查找发送者信息
            else {
                NSString* groupId = [msgMap objectForKey:@"groupId"];
                NSString*  senderId = [msgMap objectForKey:@"senderId"];
                
                NSArray *array = [groupId componentsSeparatedByString:@"_"];
                NSString *lastOne= [array objectAtIndex:[array count]-1];
               // NSString *myGroupID = [groupId stringByReplacingOccurrencesOfString:lastOne withString:DE.userId];
                NSString *myGroupID = groupId;
                NSString*  sendIdInMyContact = [NSString stringWithFormat:@"%@_%@_%@",DE.userId,senderId,myGroupID];

                Contact *conta = [ContactDao getContactByPKId:sendIdInMyContact];
                if (conta) {
                    NSDictionary *contacInfo = @{@"senderName":conta.mNAME,@"senderHeadImg":conta.mHEAD_IMG};
                    [grupContacts setValue:contacInfo forKey:senderId];
                    
                }
            }
            [msgSesion putValue:grupContacts key:@"grupContacts"];
        }
        
    }
    
}

+(BOOL)insertMessageSeesion2DB:(MessageSession*)session
{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    NSNumber *num = [NSNumber numberWithInt:session.badgeNumber];

     NSString *sql = @"INSERT INTO messagesession  (sess_id,sessionPic,text,title,badgeNumber,sessionType,oppositeId,isremind,OTHER_INFO,UPDATE_TIME) VALUES (?,?,?,?,?,?,?,?,?,?)";
     BOOL worked=[_dataBase executeUpdate:sql,session.sess_id,session.sessionPic,session.text,session.title,num,session.sessionType,session.oppositeId,session.isremind,session.otherInfo,session.upate_time];
    [_dataBase close];
    return worked;
    
}

+(BOOL)updateMessageSession:(MessageSession*)session
{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * delsql = [NSString stringWithFormat:@"DELETE from messagesession where sess_id='%@'",session.sess_id];
    NSString *sql = @"INSERT INTO messagesession  (sess_id,sessionPic,text,title,badgeNumber,sessionType,oppositeId,isremind,OTHER_INFO,UPDATE_TIME) VALUES (?,?,?,?,?,?,?,?,?,?)";
    
    [_dataBase executeUpdate:delsql];
    NSLog(@"写入数据库isremind:%@",session.isremind);
    NSNumber *num = [NSNumber numberWithInt:session.badgeNumber];
    BOOL worked=[_dataBase executeUpdate:sql,session.sess_id,session.sessionPic,session.text,session.title,num,session.sessionType,session.oppositeId,session.isremind,session.otherInfo,session.upate_time];
    [_dataBase close];
    return worked;
    
}

+(BOOL)deleteMessageSession:(NSString*)sesionId{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * delsql = [NSString stringWithFormat:@"DELETE from messagesession where sess_id='%@'",sesionId];
    BOOL worked= [_dataBase executeUpdate:delsql];
    [_dataBase close];
    NSLog(@"deleteMessageSession :::::%@",delsql);
    //删除消息时，更新消息数字
    [[NSNotificationCenter defaultCenter] postNotificationName:MESSAGE_DELETE_BROADCAST object:nil];
    return worked;
}


+(NSArray*)getMessageSession:(NSString*) ConditionSQl
{
    
    NSMutableArray *sesinList = [[NSMutableArray alloc] init];
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * sql = [NSString stringWithFormat:@"SELECT * from messagesession %@ ",ConditionSQl];
    
    FMResultSet *rs=[_dataBase executeQuery:sql];
    MessageSession *session = nil;
    while ([rs next]) {
        session = [[MessageSession alloc] init];
        session.sess_id =[rs stringForColumn:SESS_ID];
        session.sessionPic =[rs stringForColumn:SESSPICTURE];
        session.text =[rs stringForColumn:TEXT];
        session.title =[rs stringForColumn:TITLE];
        session.badgeNumber=[rs intForColumn:BADGENUMBER];
        session.sessionType =[rs stringForColumn:SESSIONTYPE];
        session.oppositeId =[rs stringForColumn:OPPOSITEID];
        session.isremind =[rs stringForColumn:ISREMIND];
        session.otherInfo=[rs stringForColumn:OTHER_INFO];
        session.upate_time =[rs dateForColumn:UPDATE_TIME];
        [sesinList addObject:session];
    };
    [rs close];
    [_dataBase close];
    return sesinList;
    
}

+(NSArray*)getAllMessageSession{
    
    NSMutableArray *sesinList = [[NSMutableArray alloc] init];
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * sql = @"SELECT * from messagesession where text!='' order by UPDATE_TIME desc";

    FMResultSet *rs=[_dataBase executeQuery:sql];
    MessageSession *session = nil;
    while ([rs next]) {
        session = [[MessageSession alloc] init];
        session.sess_id =[rs stringForColumn:SESS_ID];
        session.sessionPic =[rs stringForColumn:SESSPICTURE];
        session.text =[rs stringForColumn:TEXT];
        session.title =[rs stringForColumn:TITLE];
        session.badgeNumber=[rs intForColumn:BADGENUMBER];
        session.sessionType =[rs stringForColumn:SESSIONTYPE];
        session.oppositeId =[rs stringForColumn:OPPOSITEID];
        session.isremind =[rs stringForColumn:ISREMIND];
        session.otherInfo=[rs stringForColumn:OTHER_INFO];
        session.upate_time =[rs dateForColumn:UPDATE_TIME];
        [sesinList addObject:session];
    };
    [rs close];
    [_dataBase close];
    return sesinList;
    
}

+(MessageSession*)queryMsgSessionById:(NSString*)sesionId{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * sql = @"SELECT * from messagesession where sess_id=?";
    
    FMResultSet *rs=[_dataBase executeQuery:sql,sesionId];
    MessageSession *session = nil;
    while ([rs next]) {
        session = [[MessageSession alloc] init];
        session.sess_id =[rs stringForColumn:SESS_ID];
        session.sessionPic =[rs stringForColumn:SESSPICTURE];
        session.text =[rs stringForColumn:TEXT];
        session.title =[rs stringForColumn:TITLE];
        session.badgeNumber=[rs intForColumn:BADGENUMBER];
        session.sessionType =[rs stringForColumn:SESSIONTYPE];
        session.oppositeId =[rs stringForColumn:OPPOSITEID];
        session.isremind =[rs stringForColumn:ISREMIND];
        session.otherInfo=[rs stringForColumn:OTHER_INFO];
        session.upate_time =[rs dateForColumn:UPDATE_TIME];
    };
    [rs close];
    [_dataBase close];
    return session;

}


+(BOOL)checkTableCreatedInDb:(FMDatabase *)db
{
    NSString *createStr=@"CREATE  TABLE  IF NOT EXISTS 'messagesession' ('sess_id' text PRIMARY KEY  NOT NULL  UNIQUE ,'sessionPic' text,'text' text, 'title' text,'badgeNumber' int,'sessionType' text,'oppositeId' text,'isremind' text,'OTHER_INFO' text,'UPDATE_TIME' date)";
    BOOL worked = [db executeUpdate:createStr];
    FMDBQuickCheck(worked);
    return worked;
    
}



+(BOOL)deleteMessageByTime:(NSString*)time session:(NSString*)sesionId{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * delsql = [NSString stringWithFormat:@"delete from message  where strftime('%%Y-%%m-%%d',update_time)<? and mesSesion_sess_id = ?"];
    BOOL worked= [_dataBase executeUpdate:delsql,time,sesionId];
    [_dataBase close];
    return worked;

    
    return YES;
}

+(BOOL)deleteMessageSessionAll{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * delsql = [NSString stringWithFormat:@"DELETE from messagesession"];
    BOOL worked= [_dataBase executeUpdate:delsql];
    [_dataBase close];
    return worked;
}

+(BOOL)deleteMessageByTime:(NSString*) time{
    
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * delsql = [NSString stringWithFormat:@"delete from message  where strftime('%%Y-%%m-%%d',update_time)<?"];
    BOOL worked= [_dataBase executeUpdate:delsql,time];
    [_dataBase close];
    return worked;

}

//select sum(badgeNumber) as cc  from messagesession
//查询没有阅读的消息数20150812
+(int)queryMsgCountNoread
{
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    [self checkTableCreatedInDb:_dataBase];
    
    NSString * sql = @"select sum(badgeNumber) as cc  from messagesession";
    FMResultSet *rs=[_dataBase executeQuery:sql];
    int count = 0;
    while ([rs next]) {
        
        
        count =[rs intForColumn:@"cc"];
        
    };
    [rs close];
    [_dataBase close];
    return count;
}


@end
